package com.hy.z.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hy.z.entity.*;
import com.hy.z.exception.GlobalException;
import com.hy.z.mapper.*;
import com.hy.z.result.ResultEnum;
import com.hy.z.utils.TreeNode;
import com.hy.z.dto.UserBean;
import com.hy.z.service.ResourcesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.z.utils.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Fhy
 * @since 2021-01-14
 */
@Service
@Slf4j
public class ResourcesServiceImpl extends ServiceImpl<ResourcesMapper, Resources> implements ResourcesService {

    @Autowired
    private ResourcesMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourcesMapper roleResourcesMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


    /**
     * 根据userId查询角色
     *
     * @param userLoginParam
     */
    @Override
    public List<TreeNode> queryMenusByUserId(UserBean userLoginParam) throws Exception {
        //根据用户名查询身份
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().select(User::getUserId).eq(User::getUserName, userLoginParam.getUserName()));
        if (user == null) {
            return null;
        }
        List<Resources> resources;
        if (user.getUserId().equals(1L)) {//判断是否是管理员
            resources = menuMapper.selectList(null);
        } else {
            List<String> menuIds = getIntegers(user.getUserId());
            resources = menuMapper.selectList(Wrappers.<Resources>lambdaQuery().in(Resources::getId, menuIds));
        }
        return TreeUtil.getTreeNodes(resources);
    }


    /**
     * 获取菜单Ids
     *
     * @param userId
     * @return
     */
    private List<String> getIntegers(Long userId) throws Exception {

        //这写法其实不对还需user_role表
        UserRole userRole = userRoleMapper.selectOne(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, userId));
        if (userRole == null) {
            throw new GlobalException(ResultEnum.user_not_add_permission);
        } else {
            Role role = roleMapper.selectById(userRole.getRoleId());
            //拿到roleId再查询角色菜单表(该角色拥有的菜单信息)
            RoleResources roleResources = roleResourcesMapper.selectOne(Wrappers.<RoleResources>lambdaQuery().eq(RoleResources::getRoleId, role.getId()));
            String[] split = roleResources.getResourcesId().split(",");
            return Arrays.asList(split);
        }

    }

    /**
     * 查询所有菜单
     *
     * @return List
     */
    @Override
    public List<TreeNode> queryAllMenus() {
        List<Resources> resources = menuMapper.selectList(null);
        return TreeUtil.getTreeNodes(resources);
    }

}
